<template>
  <a-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    switchFullscreen
    @cancel="handleCancel"
    :confirmLoading="confirmLoading"
    v-drag
  >
    <div>
      <a-row style="margin-bottom: 20px" v-if="dataForm.id || state == 1 || state == 2">
        <a-col :span="24">
          <a-button v-if="dataForm.id" type="primary" @click="handleExportXls($t('其他入库单详情'))" v-has="'BisGoodsInstockController:export'">{{
            $t('导出')
          }}</a-button>
          <a-button v-if="state == 1 || state == 2" type="primary" @click="printReport" style="margin-left: 8px" v-has="'BisGoodsInstockController:print'">{{
            $t('打印')
          }}</a-button>
        </a-col>
      </a-row>
      <div>
        <a-row :gutter="10">
          <a-col :span="5" style="display: flex; align-items: center">
            <span style="white-space: nowrap; padding-right: 4px">{{ $t('仓库') }}:</span>
            <j-tree-select
              v-if="state != 1 && state != 2"
              :placeholder="$t('请选择')"
              v-model="dataForm.store"
              dict="bis_goods_store,name,id"
              pid-field="pid"
              @change="selectStore"
              pidValue="0"
              hasChildField="has_child"
            ></j-tree-select>
            <span v-if="state == 1 || state == 2">
              {{ dataForm.store_dictText }}
            </span>
          </a-col>
          <a-col :span="6" style="display: flex; align-items: center" v-if="state != 1 && state != 2">
            <span style="white-space: nowrap; padding-right: 4px">{{ $t('商品') }}:</span>
            <a-auto-complete
              :disabled="!dataForm.store"
              ref="goodsId"
              v-model="keyword"
              show-search
              option-label-prop="key"
              style="width: 100%"
              :placeholder="$t('请输入商品编码/名称/条码')"
              :filter-option="false"
              :not-found-content="null"
              :dropdown-match-select-width="false"
              :dropdown-style="{ width: '420px' }"
              @select="handleGoodsChange"
            >
              <template #dataSource>
                <a-select-opt-group v-for="group in goodsData" :key="group.title">
                  <template #label>{{$t('商品信息')}}</template>
                  <a-select-option v-for="goods in group.addGoodsList" :key="goods.id" :value="goods">
                    {{
                      goods.barcode
                        ? (goods.code ? goods.code + '(' + goods.name + ')' : goods.name) + '[' + goods.barcode + ']'
                        : goods.code
                        ? goods.code + '(' + goods.name + ')'
                        : goods.name
                    }}
                  </a-select-option>
                </a-select-opt-group>
              </template>
              <a-input-search @search="handleGoodsSearch" enter-button></a-input-search>
            </a-auto-complete>
          </a-col>
          <a-col :span="3" v-if="state != 1 && state != 2" style="display: flex; align-items: center">
            <span style="white-space: nowrap; padding-right: 4px">{{ $t('数量') }}:</span>
            <a-input-number
              :formatter="formatter"
              :parser="parser"
              ref="number"
              v-model="curGoods.number"
              style="width: 100%"
              @pressEnter="addGoods"
            />
          </a-col>
          <a-col :span="2" v-if="state != 1 && state != 2">
            <a-button type="primary" @click="addGoods">{{ $t('添加') }}</a-button>
          </a-col>
        </a-row>
        <div v-if="state != 1 && state != 2" style="margin: 10px; font-size: 14px; font-weight: bold">
          {{ $t('商品列表') }}:
        </div>
        <a-table
          :columns="columns"
          :dataSource="dataSource"
          size="middle"
          bordered
          class="j-table-force-nowrap"
          :pagination="false"
          style="padding-left: 11px"
        >
          <template slot="action" slot-scope="text, record">
            <a-icon type="close" @click="deleteGoods(record)" />
          </template>
          <template slot="number" slot-scope="text, record">
            <a-input-number
              :formatter="formatter"
              :parser="parser"
              :ref="'number' + record.sign"
              v-model="record.number"
              @change="handleAmount(record)"
              @pressEnter="nextComment(record)"
            />
          </template>
          <template slot="comment" slot-scope="text, record">
            <a-input :ref="'comment' + record.sign" v-model="record.comement" @pressEnter="nextRow(record)"></a-input>
          </template>
        </a-table>
        <div style="margin-top: 20px; font-weight: bolder">
          {{ $t('总数量') }}:{{ parseFloat(totalNum).toFixed(0) }} &nbsp; {{ $t('总金额') }}:{{ parseFloat(totalAmo).toFixed(2) }}&nbsp; {{ $t('备注') }}:&nbsp;
          <a-input
            ref="comment"
            v-if="state != 1 && state != 2"
            style="width: 300px"
            v-model="dataForm.comment"
            :placeholder="$t('请输入备注')"
          />
          <span v-if="state == 1 || state == 2">{{ dataForm.comment }}</span>
        </div>
      </div>
      <goods-print-modal ref="printModal"></goods-print-modal>
    </div>
    <template slot="footer">
      <a-button type="primary" :disabled="confirmLoading" v-if="state == 0" @click="handleOk(0)">{{
        $t('保存')
      }}</a-button>
      <a-button type="primary" :disabled="confirmLoading" v-if="state != 1 && state != 3" @click="handleOk(1)">{{
        $t('保存并审核')
      }}</a-button>
      <a-button type="primary" v-has="'GoodsInstockList:reverse'" :disabled="confirmLoading" v-if="state == 3" @click="reverse">{{
        $t('反审')
      }}</a-button>
      <a-button @click="handleCancel">{{ $t('关闭') }}</a-button>
    </template>
  </a-modal>
</template>

<script>
import { formatter, parser } from '@/api/comm'
import { getAction, httpAction, downFile } from '@/api/manage'
import AddConditionsModal from './AddConditionsModal'
import GoodsPrintModal from './GoodsPrintModal'
let that, selectedIds
export default {
  name: 'InStoreStandbyModal',
  components: {
    AddConditionsModal,
    GoodsPrintModal,
  },
  data() {
    return {
      formatter,
      parser,
      title: '',
      visible: false,
      confirmLoading: false,
      disableSubmit: false,
      dataForm: {},
      goodsData: [
        {
          addGoodsList: [],
        },
      ],
      dataSource: [],
      columns: [],
      columns1: [
        {
          title: '',
          dataIndex: 'action',
          align: 'center',
          width: 30,
          customCell: function (column) {
            return {
              style: {
                textAlign: 'center',
                color: '#1890ff',
                fontSize: '16px',
                height: '32px',
                lineHeight: '32px',
                fontWeight: 'bold',
                cursor: 'pointer',
              },
            }
          },
          scopedSlots: { customRender: 'action' },
        },
        {
          title: this.$t('序号'),
          dataIndex: '',
          key: 'rowIndex',
          align: 'center',
          width: 60,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: this.$t('商品名称'),
          dataIndex: 'goodsId_dictText',
          align: 'center',
          width: 250,
        },
        {
          title: this.$t('单位'),
          key: 'unit_dictText',
          dataIndex: 'unit_dictText',
          align: 'center',
        },
        {
          title: this.$t('规格'),
          key: 'standard',
          dataIndex: 'standard',
          align: 'center',
        },
        {
          title: this.$t('入库数量'),
          key: 'number',
          dataIndex: 'number',
          align: 'center',
          width: 100,
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
          scopedSlots: { customRender: 'number' },
        },
        {
          title: this.$t('成本'),
          key: 'unitPrice',
          dataIndex: 'unitPrice',
          align: 'center',
          customRender:(text)=>{
            return text?parseFloat(text).toFixed(2):0.00.toFixed(2)
          },
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('总金额'),
          key: 'totalAmount',
          dataIndex: 'totalAmount',
          align: 'center',
          customRender:(text)=>{
            return text?parseFloat(text).toFixed(2):0.00.toFixed(2)
          },
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('备注'),
          key: 'comement',
          dataIndex: 'comement',
          align: 'center',
          scopedSlots: { customRender: 'comment' },
        },
      ],
      columns2: [
        {
          title: this.$t('序号'),
          dataIndex: '',
          key: 'rowIndex',
          align: 'center',
          width: 60,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: this.$t('商品编码'),
          dataIndex: 'goodsCode',
          align: 'center',
          width: 90,
        },
        {
          title: this.$t('商品名称'),
          dataIndex: 'goodsId_dictText',
          align: 'center',
          width: 250,
        },
        {
          title: this.$t('单位'),
          key: 'unit_dictText',
          dataIndex: 'unit_dictText',
          align: 'center',
        },
        {
          title: this.$t('规格'),
          key: 'standard',
          dataIndex: 'standard',
          align: 'center',
        },
        {
          title: this.$t('入库数量'),
          key: 'number',
          dataIndex: 'number',
          align: 'center',
          customRender:(text)=>{
            return text?parseFloat(text).toFixed(0):0.00.toFixed(0)
          },
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('成本'),
          key: 'unitPrice',
          dataIndex: 'unitPrice',
          align: 'center',
          customRender:(text)=>{
            return text?parseFloat(text).toFixed(2):0.00.toFixed(2)
          },
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('总金额'),
          key: 'totalAmount',
          dataIndex: 'totalAmount',
          align: 'center',
          customRender:(text)=>{
            return text?parseFloat(text).toFixed(2):0.00.toFixed(2)
          },
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
      ],
      columns3: [
        {
          title: this.$t('业务前库存'),
          key: 'beforeNum',
          dataIndex: 'beforeNum',
          align: 'center',
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('业务后库存'),
          key: 'afterNum',
          dataIndex: 'afterNum',
          align: 'center',
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
      ],
      columns4: [
        {
          title: this.$t('备注'),
          key: 'comement',
          dataIndex: 'comement',
          align: 'center',
        },
      ],
      url: {
        add: '/goods/bisGoodsInstock/add',
        edit: '/goods/bisGoodsInstock/edit',
        exportXlsUrl: '/goods/bisGoodsInstock/detailExportXls',
      },
      totalNum: 0,
      totalAmo: 0,
      state: 0,
      curGoods: {},
      keyword: '',
    }
  },
  created() {
    that = this
  },
  methods: {
    add(obj) {
      selectedIds = []
      let record = {}
      if(obj){
        if(obj.storeId){
          record.store = obj.storeId
        }
        if(obj.selectedIds){
          selectedIds = obj.selectedIds
        }
      }
      that.edit(record)
    },
    edit(record, state) {
      that.visible = true
      that.confirmLoading = false
      that.keyword = ''
      that.dataForm = {}
      that.dataSource = []
      that.curGoods = {}
      that.totalAmo = 0
      that.totalNum = 0
      that.goodsData = []
      that.goodsData.push({ addGoodsList: [] })
      if (state == undefined) {
        that.state = 0
        that.columns = that.columns1
      } else {
        that.state = state
        if (record.state == '1') {
          that.columns = that.columns2.concat(that.columns3, that.columns4)
        } else {
          that.columns = that.columns2.concat(that.columns4)
        }
      }
      if(!record.id&&selectedIds.length>0){
        let dataSourceTwo = []
        getAction('/goods/bisGoodsInfor/list', {id: selectedIds.join(','), pageSize: 1000}).then((res) => {
          if(res.success){
            res.result.records.forEach((col) => {
              let aa = {
                goodsId: col.id,
                goodsCode: col.code,
                goodsId_dictText: col.name,
                number: '',
                unitPrice: '' + col.cost,
                totalAmount: '',
                supplier_dictText: col.supplierId_dictText,
                supplier: col.supplierId,
                unit_dictText: col.unit_dictText,
                standard: col.standard,
                comement: '',
              }
              dataSourceTwo.push(aa)
            })
            dataSourceTwo.forEach((dst) => {
              let x = that.dataSource.findIndex((ds) => {
                return ds.goodsId == dst.goodsId
              })
              if (x == -1) {
                that.dataSource.push(dst)
              }
            })
            that.dataSource.forEach((d, i) => {
              d.sign = i
            })
          }
        })
      }
      that.dataForm = Object.assign({}, record)
      if (that.dataForm.id) {
        getAction('/goods/bisGoodsInstock/queryBisGoodsInstockDetailsByMainId', { id: that.dataForm.id }).then((res) => {
          if (res.success) {
            that.dataSource = res.result
            that.dataSource.forEach((col, i) => {
              col.sign = i
              that.totalNum += col.number
              that.totalAmo += col.totalAmount
            })
          }
        })
      }
    },
    addGoods() {
      if (that.dataForm.store == '' || that.dataForm.store == undefined) {
        that.$message.warning(that.$t('请选择仓库'))
        return
      } else {
        let obj = {
          goodsId: that.curGoods.id,
          goodsCode: that.curGoods.code,
          goodsId_dictText: that.curGoods.name,
          number: that.curGoods.number,
          unitPrice: that.curGoods.cost,
          totalAmount:
            that.curGoods.number && that.curGoods.cost
              ? (parseInt(that.curGoods.number) * parseFloat(that.curGoods.cost))
              : '0.00',
          unit_dictText: that.curGoods.unit_dictText,
          standard: that.curGoods.standard,
          comement: '',
        }
        let x = that.dataSource.findIndex((d) => {
          return d.goodsId == obj.goodsId
        })
        if (x == -1) {
          that.dataSource.unshift(obj)
          that.totalAmo = 0
          that.totalNum = 0
          that.dataSource.forEach((d, i) => {
            d.sign = i
            that.totalNum = parseFloat(d.number) + parseFloat(that.totalNum)
            that.totalAmo = parseFloat(d.totalAmount) + parseFloat(that.totalAmo)
          })
        } else {
          that.$message.warning(`${obj.goodsCode}${obj.goodsId_dictText}` + that.$t('商品已存在'))
        }
        that.$nextTick(() => {
          that.goodsData=[]
          that.curGoods = {}
          that.keyword = ''
          that.$refs.goodsId.focus()
        })
      }
    },
    reverse(){
      httpAction('/goods/bisGoodsInstock/reverse', {id:that.dataForm.id}, 'put').then((res) => {
        if (res.success) {
          that.close()
          that.$message.success(res.message)
        } else {
          that.confirmLoading = false
          that.$message.warning(res.message)
        }
      })
    },
    handleGoodsSearch() {
      that.getGoodsList(that.keyword)
    },
    getGoodsList(value) {
      let querydata = {}
      querydata.pageNo = 1
      querydata.pageSize = 10
      querydata.goodsInfo = value
      querydata.form = '1,7,11,19'
      that.goodsData = []
      getAction('/goods/bisGoodsInfor/list', querydata).then((res) => {
        if (res.success) {
          if (res.result.total > 0) {
            let goodsList = res.result.records
            if (goodsList.length > 1) {
              that.goodsData.push({ addGoodsList: goodsList })
            } else {
              that.handleGoodsChange(goodsList[0])
            }
          }else{
            that.$message.warn(that.$t('未找到符合的商品'))
            that.keyword=''
          }
        }
      })
    },
    handleAmount(record) {
      if (record.number != '') {
        record.totalAmount = parseFloat(record.number) * parseFloat(record.unitPrice)
        if (isNaN(record.totalAmount)) {
          record.totalAmount = ''
          return
        }
        that.totalNum = 0
        that.totalAmo = 0
        that.dataSource.forEach((res) => {
          if (res.number != '') {
            that.totalNum = parseFloat(res.number) + parseFloat(that.totalNum)
            that.totalAmo = parseFloat(res.totalAmount) + parseFloat(that.totalAmo)
          }
        })
      } else {
        record.totalAmount = 0
        that.totalNum = 0
        that.totalAmo = 0
        that.dataSource.forEach((res) => {
          if (res.number != '') {
            that.totalNum = parseFloat(res.number) + parseFloat(that.totalNum)
            that.totalAmo = parseFloat(res.totalAmount) + parseFloat(that.totalAmo)
          }
        })
      }
    },
    deleteGoods(b) {
      let ind = that.dataSource.findIndex((d) => {
        return b.goodsId == d.goodsId
      })
      that.dataSource.splice(ind, 1)
      that.dataSource.forEach((d, i) => {
        d.sign = i
      })
    },
    handleOk(state) {
      let querydata = {}
      querydata = that.dataForm
      if (querydata.store == undefined) {
        that.$message.warning(that.$t('请选择仓库'))
        that.confirmLoading = false
        return
      }
      if (that.dataSource.length == 0) {
        that.$message.warning(that.$t('商品不能为空'))
        return
      }
      let arr = that.dataSource.filter((d) => {
        return d.number == '' || d.number == null || d.number == '0'
      })
      if (arr.length > 0) {
        if ((arr[0].number == '' || arr[0].number == null) && arr[0].number !== 0) {
          that.$message.warning('['+arr[0].goodsId_dictText+'] '+that.$t('入库数量不能为空'))
          that.$refs['number' + arr[0].sign].focus()
          return
        }
        if (arr[0].number == '0') {
          that.$message.warning('['+arr[0].goodsId_dictText+'] '+that.$t('入库数量不能为0'))
          that.$refs['number' + arr[0].sign].focus()
          return
        }
        return
      }
      that.confirmLoading = true
      querydata.bisGoodsInstockDetailsList = that.dataSource
      querydata.state = state
      querydata.inType = '2'
      let httpurl = ''
      let method = ''
      if (!that.dataForm.id) {
        httpurl += that.url.add
        method = 'post'
      } else {
        httpurl += that.url.edit
        method = 'put'
      }
      httpAction(httpurl, querydata, method).then((res) => {
        if (res.success) {
          that.close()
          that.$message.success(res.message)
        } else {
          that.confirmLoading = false
          that.$message.warning(res.message)
        }
      })
    },
    handleCancel() {
      that.close()
    },
    close() {
      selectedIds = []
      that.$emit('ok')
      that.visible = false
    },
    handleExportXls(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = that.$t('导出文件')
      }
      let param = {}
      param.orderId = that.dataForm.id
      downFile(that.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          that.$message.warning(that.$t('文件下载失败'))
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    printReport() {
      that.$refs.printModal.show(that.dataForm, 6)
    },
    selectStore() {
      that.$nextTick(() => {
        that.$refs.goodsId.focus()
      })
    },
    handleGoodsChange(value) {
      that.curGoods = JSON.parse(JSON.stringify(value))
      that.keyword = that.curGoods.name
      that.$refs.number.focus()
    },
    nextComment(record) {
      that.$refs['comment' + record.sign].focus()
    },
    nextRow(record) {
      if (record.sign == that.dataSource.length - 1) {
        that.$refs.comment.focus()
      } else {
        that.$refs['number' + (record.sign + 1)].focus()
      }
    },
  },
}
</script>

<style scoped>
</style>